﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using XbdSoft.WPFVersion.ViewModel;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Composite.Presentation.Commands;
using XbdSoft.WPFVersion.Common;
using System.ComponentModel;
using XbdSoft.Contract;
using XbdSoft.Client;

namespace XbdSoft.WPFVersion.View
{
    /// <summary>
    /// Interaction logic for SearchResourceView.xaml
    /// </summary>
    public partial class SearchResourceView : UserControl
    {  
        #region Fields
        protected readonly IEventAggregator EventAggregator = null;
        protected readonly IUnityContainer Container = null; 
        #endregion

        private const int PageSize = 10;

        public SearchResourceViewModel ViewModel = null; 
        public SearchResourceView()
        {
            EventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
            Container = ServiceLocator.Current.GetInstance<IUnityContainer>();
            InitializeComponent();
            ViewModel = Container.Resolve<SearchResourceViewModel>();       
            DataContext = ViewModel;
            CanShow = false;
            HasLoaded = false;
            //EventAggregator.GetEvent<TryListenEvent>().Subscribe(TryListenEvent_Published);
            //ViewModel.PropertyChanged += new PropertyChangedEventHandler(ViewModel_PropertyChanged);
        }

        public void TryListenEvent_Published(TryListenEventArgs e)
        {
            var id = e.ResourceID;
            try
            {
                var url = string.Empty;
                using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
                {
                    url = service.Object.GetDownloadUrl(id);
                }
                winMediaPlayer.Url = url;
                winMediaPlayer.Play();
                winMediaPlayerHost.Visibility = System.Windows.Visibility.Visible;
            }
            catch
            {
                winMediaPlayer.Close();
            }
        }

        public ICommand TryListenCommand { get; set; }
        protected virtual void OnTryListen(object args)
        {
            var id = (int)args;
            try
            {
                var url = string.Empty;
                using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
                {
                    url = service.Object.GetDownloadUrl(id);
                }
                winMediaPlayer.Url = url;
                winMediaPlayer.Play();
                winMediaPlayerHost.Visibility = System.Windows.Visibility.Visible;
            }
            catch
            {
                winMediaPlayer.Close();
            }
        }

        public void PauseTryListen()
        {
            winMediaPlayer.Url = "";
            winMediaPlayer.Pause(); 
            winMediaPlayer.Close();
            winMediaPlayerHost.Visibility = System.Windows.Visibility.Collapsed;
        }

        public ICommand DownloadCommand { get; set; }
        protected virtual void OnDownloadCommand(object args)
        {
            var id = (int)args;
            try
            {
                var resource = ViewModel.AudioResources.SingleOrDefault(r => r.ID == id);
                if (resource != null)
                {
                    var eventArgs = new DownloadResourceEventArgs() { Resource = resource };
                    EventAggregator.GetEvent<DownloadResourceEvent>().Publish(eventArgs);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void KeyWordTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ViewModel.KeyWord = KeyWordTextBox.Text;
                e.Handled = true;
            }
        }

        private void KeyWordTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            ViewModel.SetKeyWord(KeyWordTextBox.Text.Trim());
        }

        private void Root_Loaded(object sender, RoutedEventArgs e)
        {
            if (CanShow && !HasLoaded)
            {
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
                backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
                backgroundWorker.RunWorkerAsync();
            } 
            
        } 

        void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MaskBorder.Visibility = System.Windows.Visibility.Collapsed;
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ViewModel.Refresh();
            TryListenCommand = ViewModel.TryListenCommand;
            DownloadCommand = new DelegateCommand<object>(OnDownloadCommand, o => true);
            TryListenCommand = ViewModel.TryListenCommand; //new DelegateCommand<object>(OnTryListen); //
            HasLoaded = true;
        }

        public bool CanShow { get; set; }
        public bool HasLoaded { get; private set; }
         
    }
}
